<template>
  <div class="app-container customer-div">
    <el-tabs v-model="tab">
      <el-tab-pane label="客户分析" name="a1">
        <div style="margin-top: 20px">
          <!--搜索-->
          <el-form :inline="true" :model="params" size="mini" label-width="100px">
            <div>
              <el-form-item label-width="0">
                <el-radio-group v-model="params.timeType" @change="changeTimeType">
                  <el-radio-button label="year">按年查询</el-radio-button>
                  <el-radio-button label="month">按月查询</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </div>
            <el-form-item label="成交业务员：">
              <el-select v-model="params.userId" filterable placeholder="请选择" clearable>
                <el-option
                        v-for="item in userOptionList"
                        :key="item.userId"
                        :label="item.userName"
                        :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="负责业务员：">
              <el-select v-model="params.chargeId" filterable placeholder="请选择" clearable>
                <el-option
                        v-for="item in userOptionList"
                        :key="item.userId"
                        :label="item.userName"
                        :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="查询日期：" v-if="params.timeType == 'year'">
              <el-date-picker
                      :clearable="false"
                      style="width:150px"
                      v-model="params.analysisTime[0]"
                      value-format="yyyy"
                      type="year"
                      :picker-options="startDatePicker"
                      placeholder="开始年份">
              </el-date-picker>
              <span style="padding:0 10px">-</span>
              <el-date-picker
                      value-format="yyyy"
                      :clearable="false"
                      style="width:150px"
                      v-model="params.analysisTime[1]"
                      type="year"
                      :picker-options="endDatePicker"
                      placeholder="结束年份">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="查询日期：" v-if="params.timeType == 'month'">
              <div style="position: relative">
                <el-date-picker
                        value-format="yyyy-MM"
                        :clearable="false"
                        v-model="params.analysisTime"
                        type="monthrange"
                        range-separator="-"
                        start-placeholder="开始月份"
                        end-placeholder="结束月份">
                </el-date-picker>
              </div>

            </el-form-item>
            <el-form-item>
              <el-button
                      @click="handleSearchList()"
                      type="primary">
                查询
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <!--数据列表-->
        <div class="table-container">
          <el-table
                  v-loading="loading"
                  :data="list"
                  style="margin-top: 20px" :style="{width:title.length * 180 +100 + 'px'}">
            <el-table-column
                    show-overflow-tooltip
                    :key="item.key"
                    v-for="item in title"
                    :prop="item.keyName"
                    :label="item.labelName"
                    align="center"
                    :width="item.keyName == 'customerName' ? 300 : 180">
            </el-table-column>
            <el-table-column
                    fixed="right"
                    label="操作"
                    align="center"
                    min-width="150">
              <template slot-scope="scope">
                <el-button
                        @click="toInfo(scope.row)"
                        type="text"
                        size="mini">报表
                </el-button>
                <el-button
                        @click="changeTab(scope.row)"
                        type="text"
                        size="mini">明细
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
                  background
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  layout="total, sizes,prev, pager, next,jumper"
                  :current-page.sync="params.pageNum"
                  :page-size="params.pageSize"
                  :page-sizes="[10,15,20]"
                  :total="count">
          </el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="客户成交明细分析" name="a2">
        <div style="margin-top: 20px">
          <!--搜索-->
          <el-form :inline="true" :model="params2" size="mini" label-width="100px">
            <el-form-item label="成交业务员：">
              <el-select v-model="params2.userId" filterable placeholder="请选择" clearable>
                <el-option
                        v-for="item in userOptionList"
                        :key="item.userId"
                        :label="item.userName"
                        :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="负责业务员：">
              <el-select v-model="params2.chargeId" filterable placeholder="请选择" clearable>
                <el-option
                        v-for="item in userOptionList"
                        :key="item.userId"
                        :label="item.userName"
                        :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="查询日期：">
              <el-date-picker
                      v-model="params2.createTime"
                      type="daterange"
                      format="yyyy 年 MM 月 dd 日"
                      value-format="yyyy-MM-dd"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="客户编号：">
              <el-input v-model="params2.customerNumber"></el-input>
<!--              <el-select-->
<!--                      clearable-->
<!--                      v-model="params2.customerId"-->
<!--                      filterable-->
<!--                      remote-->
<!--                      reserve-keyword-->
<!--                      placeholder="请输入关键词"-->
<!--                      :remote-method="remoteMethod"-->
<!--                      :loading="loading3">-->
<!--                <el-option-->
<!--                        v-for="item in options"-->
<!--                        :key="item.customerId"-->
<!--                        :label="item.customerName"-->
<!--                        :value="item.customerId">-->
<!--                </el-option>-->
<!--              </el-select>-->
            </el-form-item>

            <el-form-item label="类型：">
              <el-select v-model="params2.priceType" filterable placeholder="请选择" clearable>
                <el-option key="priceUpNum" label="紧俏" value="priceUpNum"></el-option>
                <el-option key="priceStableNum" label="平稳" value="priceStableNum"></el-option>
                <el-option key="priceDownNum" label="滞销" value="priceDownNum"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button
                      @click="handleSearchList2()"
                      type="primary">
                查询
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <!--数据列表-->
        <div class="table-container">
          <el-table
                  v-loading="loading2"
                  :data="list2"
                  style="margin-top: 20px">
            <el-table-column
                    label="日期"
                    prop="createTime"
                    align="center"
                    width="150">
            </el-table-column>
            <el-table-column
                    prop="customerKingNumer"
                    label="金蝶代码"
                    align="center"
                    width="150">
            </el-table-column>
            <el-table-column
                    prop="customerName"
                    label="客户编号"
                    align="center"
                    width="300">
              <template slot-scope="scope">
                <div>{{scope.row.customerNumber }}</div>
                <!--是否有权限-->
                <div v-if="scope.row.isShowCustomerName">{{scope.row.customerName}}</div>
              </template>
            </el-table-column>
            <el-table-column
                    prop="goodsName"
                    label="品类"
                    align="center"
                    width="150">
            </el-table-column>
            <el-table-column
                    prop="goodsSn"
                    label="牌号"
                    align="center"
                    width="300">
            </el-table-column>
            <el-table-column
                    prop="goodsPrice"
                    label="合同单价"
                    align="center"
                    width="150">
            </el-table-column>
            <el-table-column
                    prop="goodsNum"
                    label="数量"
                    align="center"
                    width="150">
            </el-table-column>
            <el-table-column
                    prop="priceType"
                    label="类型"
                    align="center"
                    width="150">
            </el-table-column>
            <el-table-column
                    prop="userName"
                    label="成交业务员"
                    align="center"
                    width="150">
            </el-table-column>
            <el-table-column
                    prop="chargeName"
                    label="负责人"
                    align="center"
                    width="150">
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
                  background
                  @size-change="handleSizeChange2"
                  @current-change="handleCurrentChange2"
                  layout="total, sizes,prev, pager, next,jumper"
                  :current-page.sync="params2.pageNum"
                  :page-size="params2.pageSize"
                  :page-sizes="[10,15,20]"
                  :total="count2">
          </el-pagination>
        </div>
      </el-tab-pane>

    </el-tabs>

  </div>
</template>

<script>
    import { getOrderUsersList,analysisOrderList,getCustomerOption,analysisOrderDetailList} from '@/api/partner'
    import {formatDate} from '@/utils/date';
    import store from '@/store'
    import { mapGetters } from 'vuex'

    export default {
        name: "saleReport",
        data(){
            return{
                roles:store.getters.roles ? store.getters.roles : [],
                params:{
                  pageNum:1,
                  pageSize:10,
                  userId:'',
                  chargeId:'',
                  analysisTime:[new Date().getFullYear() + '',new Date().getFullYear() + ''],
                  timeType:'year'
                },
                list:[],
                count:0,
                loading:false,
                tab:'a1',
                startDatePicker: this.beginDate(),
                endDatePicker: this.processDate(),
                userOptionList:[],
                title:[],

                list2:[],
                count2:0,
                loading2:false,
                params2:{
                  pageNum:1,
                  pageSize:10,
                  userId:'',
                  chargeId:'',
                  createTime:[],
                  customerId: '',
                  priceType:'',
                  customerNumber:''
                },
              loading3:false,
              options:[]
            }
        },
        computed: {
          ...mapGetters([
            'name',
            'mobile',
            'userId'
          ]),


        },
        created() {
          let now = new Date();
          let nowMonth = now.getMonth(); //当前月
          let nowYear = now.getFullYear(); //当前年
          //本月的开始时间
          let monthStartDate = new Date(nowYear, nowMonth, 1);
          //本月的结束时间
          let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
          let startDate = formatDate(monthStartDate, 'yyyy-MM-dd');
          let endDate = formatDate(monthEndDate, 'yyyy-MM-dd');
          this.params2.createTime = [startDate,endDate];

          this.getUserOptionList();
          this.getListData();
          this.getListData2();
        },
        filters: {
            formatTime(time) {
                let date = new Date(time);
                return formatDate(date, 'yyyy-MM-dd')
            },
        },
        methods:{
          handleClick(){

          },
          changeTab(item){
            console.log(item.customerId)
            this.params2.customerId = item.customerId;
            this.params2.createTime = JSON.parse(JSON.stringify(this.params.analysisTime));
            if(this.params.timeType == 'month'){
              this.params2.createTime[0] = formatDate(new Date(this.params2.createTime[0]),'yyyy-MM-dd');
              let year = new Date(this.params2.analysisTime[1]).getFullYear();
              let month = new Date(this.params2.analysisTime[1]).getMonth() + 1;
              let day;
              if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
                day = 31
              }else if(month == 4 || month == 6 || month == 9 || month == 11 ){
                day = 30
              }else {
                if(year%4==0&&year%100!=0||year%400==0){
                  day = 29
                }else{
                  day = 28
                }
              }
              this.params2.createTime[1] = formatDate(new Date(year+'-'+month+'-'+day),'yyyy-MM-dd');
            }else if(this.params.timeType == 'year'){
              this.params2.createTime[0] = formatDate(new Date(this.params2.createTime[0]),'yyyy-MM-dd');
              this.params2.createTime[1] = formatDate(new Date(this.params2.createTime[1] + '-12-31'),'yyyy-MM-dd')
            }
            this.options = [];
            this.options.push({customerId:item.customerId,customerName:item.customerName})
            this.tab = 'a2';
            this.handleSearchList2()
          },
          handleSearchList2(){
            this.params2.pageNum = 1;
            this.getListData2();
          },

          handleSizeChange2(val){
            this.params2.pageNum = 1;
            this.params2.pageSize = val;
            this.getListData2();
          },
          handleCurrentChange2(val){
            this.params2.pageNum = val;
            this.getListData2();
          },

          getListData2(){
            this.loading2 = true;
            analysisOrderDetailList(this.params2).then((res)=>{
              this.list2 = res.list;
              this.count2 = res.count;
              this.loading2 = false;
            }).catch(()=>{
              this.loading2 = false;
            })
          },
          remoteMethod(query) {
            if (query !== '') {
              this.loading3 = true;
              getCustomerOption({keywords:query}).then((res)=>{
                this.options = res;
                this.loading3 = false;
              });
            } else {
              this.options = [];
            }
          },
          //获取员工下拉选项
          getUserOptionList(){
            getOrderUsersList().then((res)=>{
              this.userOptionList = res;
            })
          },
          //切换查询类型
          changeTimeType(val){
              if(val == 'year'){
                this.params.analysisTime.splice(0,1,new Date(this.params.analysisTime[0]).getFullYear() + '' );
                this.params.analysisTime.splice(1,1,new Date(this.params.analysisTime[1]).getFullYear() + '')
              }else if(val == 'month'){
                this.params.analysisTime.splice(0,1,new Date(this.params.analysisTime[0]).getFullYear() + '-' + '01');
                this.params.analysisTime.splice(1,1,new Date(this.params.analysisTime[1]).getFullYear() + '-' + '12')
              }
              this.handleSearchList()
          },
          beginDate(){
            const self = this;
            return {
              disabledDate(time){
                if (self.params.analysisTime[1]) {  //如果结束时间不为空，则小于结束时间
                  let starttime = new Date(time).getFullYear() + '-' + '01';
                  return new Date(self.params.analysisTime[1]).getTime() < new Date(starttime).getTime()
                } else {
                  // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
                }
              }
            }
          },
          processDate() {
            const  self = this;
            return {
              disabledDate(time) {
                if (self.params.analysisTime[0]) {  //如果开始时间不为空，则结束时间大于开始时间
                  let starttime = new Date(self.params.analysisTime[0]).getFullYear() + '-' + '01';
                  return new Date(starttime).getTime() > time.getTime()
                } else {
                  // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
                }
              }
            }
          },

          handleSearchList(){
                this.params.pageNum = 1;
                this.getListData();
            },

            handleSizeChange(val){
                this.params.pageNum = 1;
                this.params.pageSize = val;
                this.getListData();
            },
            handleCurrentChange(val){
                this.params.pageNum = val;
                this.getListData();
            },

            getListData(){
              this.loading = true;
              analysisOrderList(this.params).then((res)=>{
                this.list = res.list;
                this.count = res.count;
                this.title = res.title;
                this.loading = false;
              }).catch(()=>{
                this.loading = false;
              })
            },

          toInfo(item){
            let routeData = this.$router.resolve({name:'customerAnalysisInfo',query:{customerId:item.customerId}});
            window.open(routeData.href);
          },

        },
    }
</script>

<style scoped lang="scss">
  .avatar-uploader{
    margin-bottom:10px;
    display: inline-block;
    width:80px;
    height:80px;
    border:1px solid #DCDFE6;
    text-align: center;
    line-height: 80px;
  }
</style>
